package com.example.taobaounion.view_component;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;

import androidx.annotation.Nullable;

import com.example.taobaounion.R;

public class LoadingView extends androidx.appcompat.widget.AppCompatImageView {
    public static int DEGREES = 30;
    private Boolean mNeedRotate;

    public LoadingView(Context context) {
        this(context, null);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setImageResource(R.mipmap.loading);

    }


    @Override
    protected void onDraw(Canvas canvas) {
        canvas.rotate(DEGREES, getWidth() >> 1, getHeight() >> 1);
        super.onDraw(canvas);
    }


    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();

        startRotate();
    }

    private void startRotate() {
        mNeedRotate = true;

        post(new Runnable() {
            @Override
            public void run() {
                DEGREES += 10;

                if (DEGREES >= 360) {
                    DEGREES = 0;
                }

                invalidate();

                // 判断是否要继续选择
                // 如果不可见或者DetachedForm Window
                // 停止旋转

                if (getVisibility() != VISIBLE && mNeedRotate) {
                    removeCallbacks(this);
                } else {
                    postDelayed(this, 50);
                }
            }
        });
    }

    void stopRotate() {
        mNeedRotate = false;
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        stopRotate();
    }
}
